/*****目标团队--对抗演练*****/
<template><!---->
    <div>
    <Row class="targetHeader">
        <Select filterable v-model="queryTargetTeamInfo.teamName"
                style="width: 150px; margin-right:15px;"
                @on-change="searchTargetTeam" clearable
                placeholder="请选择团队">
            <Option v-for="item in accessGroupList" :value="item.name" :key="item.id" :title="item.name">{{ item.name }}</Option>
        </Select>
        <Select filterable v-model="queryTargetTeamInfo.name"
                style="width: 150px; margin-right:15px;"
                @on-change="searchTargetTeam" clearable
                placeholder="请选择题目">
            <Option v-for="item in allTargetTeamData" :value="item.name" :key="item.id" :title="item.name">{{ item.name }}</Option>
        </Select>
		<span v-show="type==0&&this.drillDetail.progress==2&&this.hlConfig==1" style="width: 150px; margin-right:15px;font-size:14px;font-weight:700;color:#515a6e">当前周期：第{{number}}周期</span>
      <!--<DatePicker format="yyyy-MM-dd HH:mm:ss" type="daterange"  placeholder="选择日期" style="width: 200px"
                  @on-change="searchTargetPrjD"></DatePicker>-->
      <!--<Input v-model.trim="searchPrjString" search placeholder="题目显示名称" style="width: 200px" @on-search="searchTargetPrj"  />-->
      <Page :total=	targetTeamTotal
            show-total show-elevator @on-page-size-change="getTargetSize"
            @on-change="getTargetPage" style="float: right">
      </Page>
    </Row>
    <!--<Table border :columns="targetTeamCol4" :data="targetTeamData" v-if="type == 4"></Table>-->
    <!--<card-list :columns="targetTeamCol4" :data="targetTeamData" v-if="type == 4"></card-list>-->
    <!--<Table border :columns="targetTeamCol1" :data="targetTeamData" v-else-if="type == 1"></Table>-->
    <!--<card-list :columns="targetTeamCol1" :data="targetTeamData" v-else-if="type == 1"></card-list>-->
    <!--<Table border :columns="targetTeamCol" :data="targetTeamData" v-else></Table>-->
    <TableList :columns="targetTeamCol" :data="targetTeamData"></TableList>
    </div>
</template>

<script>
  import {getTargetTeamList,addTargetTeam,modifyTargetTeam,getTargetTeamInfo,delTargetTeam,queryVmWithParty,getSceneCycle} from '@/api/drill_compete'
  import {queryCtfList} from '@/api/question'
  import {getaccessgrouplist} from '@/api/access_new'
	export default {
  name: 'scenes',
    props:['type','poll','drillDetail','hlConfig'], //接受演练竞赛类型
    components:{},
	data(){
	  	return {
			number:0,
		  	routeParams:{
	          id:this.$route.query.id,
	          prjid:this.$route.query.prjid
	        },
	        targetModal:{
	        	show:false,
	        	title:'',
	        	loading:true,
	        	type:1 //1添加，2修改
	        },
			accessGroupList:[],
	        vmlists:[],
	        teamlists:[],
			queryTargetTeamInfo:{
				pageIndex:1,
				pageSize:10,
				sceneId:this.$route.query.id,
				projectId:this.$route.query.prjid
			},
	        questionList:[],
	        formValidate: {
	          //"createTime": "2020-02-10T03:35:50.081Z",
			  //"creator": "string",
			  "description": "", //目标描述
			  "externalIp": "", //对外ip
			  "externalPort": 1, //对外端口
			  //"ip": "string",
			  "name": "", //目标名称
			  //"password": "string",
			  //"port": "string",
			  "projectId": this.$route.query.prjid,
			  "questionId": '', //题目id
			  "sceneId": this.$route.query.id,
			  "score": 0,
			  //"status": 0, //状态：1 正常/防护成功，2 被攻破，3 服务异常，4 被攻破+服务异常
			  "teamId": "",
			  "teamName": "",
			  "type": 0, //目标类型：0.单个虚拟机、1.多个虚拟机flag相同、2.多个虚拟机flag不同、3.文件类型
			  //"user": "string",
			  "visibility": 0, //可见性：是否可见- 0.不可见 1可见
			  "vmId": ""
	        },
	        ruleValidate: {
	          name: [
	            { required: true, message: '名字不能为空', trigger: 'change' }
	          ],
	          description: [
	            { required: true, message: '请输入描述信息', trigger: 'change' }
	          ],
	          type: [
	            { required: true,type:'number',message: '请选择靶标类型', trigger: 'change' },
	          ],
	          score:[
	            { required: true, type:'number',message: '请输入分值', trigger: 'change'}
	          ],
	          externalIp:[
	          	{ required: true, message: '请输入对外IP', trigger: 'change'}
	          ],
	          externalPort:[
	          	{ required: true, type:'number',message: '请输入对外端口', trigger: 'change'}
	          ],
	//        questionId:[
	//        	{ required: true, message: '请选择题目', trigger: 'change'}
	//        ],
	          visibility:[
	          	{ required: true, type:'number',message: '请选择', trigger: 'change'}
	          ],
	          vmId:[
	          	{ required: true, message: '请选择虚拟机', trigger: 'change'}
	          ],
	          teamId:[
	          	{ required: true, message: '请选择团队', trigger: 'change'}
	          ],
	        },
	        initTargetObjData:{
	          "createtime": "",
	          "createuser": localStorage.getItem('username'),
	          "frequency": 0,
	          "id": "",
	          "isshow": 1,
	          "lastupdatetime": "",
	          "modifier": "",
	          "sceneid": "",
	          "targetdes": "",
	          "targetname": "",
	          "targetsubmittype":0,
	          "targettype": 0,
	          "teamid": "",
	          "type": 0,
	          "uri": "",
	          "vmid": "",
	          "score":'0'
	        },
	        querytime:{},
	        targetTeamCol:[
	//        {
	//          type: 'index',
	//          align: 'center',
	//          ellipsis:true,
	////          width:60
	//        },
			 {
	            title:'团队名称',
	            key:'teamName',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            width:100
	          },
	          {
	            title:'题目显示名称',
	            key:'name',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            placement:'top-left',
                width:240
	          },
//	          {
//	            title:'靶标类型',
//	            key:'type',
//	            align:'center',
//	            render:(h, params) => {
//	              return h('span',this.typeFilter(params.row.type))
//	            }
//	          },
	//		  {
	//          title:'IP地址',
	//          key:'ip',
	//          align:'center',
	//          ellipsis:true,
	//          tooltip:true,
	//        },
	//        {
	//          title:'端口',
	//          key:'port',
	//          align:'center',
	//          ellipsis:true,
	//          tooltip:true,
	//        },
	//        {
	//          title:'对外IP',
	//          key:'externalIp',
	//          align:'center',
	//          ellipsis:true,
	//          tooltip:true,
	//        },
	//        {
	//          title:'对外端口',
	//          key:'externalPort',
	//          align:'center',
	//          ellipsis:true,
	//          tooltip:true,
	//        },
	          {
	            title:'分值',
	            key:'score',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            width:60
	          },
	          {
	            title:'状态',
	            key:'status',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            placement:'top-right',
	            render:(h,params) => {
	            	return h('Tag',{
	            		props:{
	            			color:this.statusFilter(params.row.status,'color')
	            		}
	            	},this.statusFilter(params.row.status,'text'))
	            }
	          },
	          {
	            title:'题目最后得失分时间',
	            key:'lastScoreTime',
	            align:'center',
	            ellipsis:true
	          },
	        ],
	        targetTeamCol4:[ //渗透演练 type == 4
			 {
	            title:'团队名称',
	            key:'teamName',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            width:150
	          },
            {
                   title:'攻破用户',
                   key:'userName',
                   align:'center',
                   ellipsis:true,
                   tooltip:true,
                   width:150
                 },
	          {
	            title:'题目显示名称',
	            key:'name',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	//          width:100
	          },
	          {
	            title:'分值',
	            key:'score',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	          },
	          {
	            title:'攻破者',
	            key:'userName',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	          },
	          {
	            title:'状态',
	            key:'status',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            render:(h,params) => {
	            	return h('Tag',{
	            		props:{
	            			color:this.statusFilter(params.row.status,'color')
	            		}
	            	},(params.row.status == 2 || params.row.status == 4) ? '已攻破' : '未攻破')
	            }
	          },
	          {
	            title:'攻破时间',
	            key:'lastScoreTime',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	          },
	        ],
	        targetTeamCol1:[ //攻防赛 type == 1 //题目显示名称、团队名称、剩余分数、每周期分数、靶标状态、最后一次扣分时间
			 {
	            title:'团队名称',
	            key:'teamName',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            width:100
	          },
	          {
	            title:'题目显示名称',
	            key:'name',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	//          width:100
	          },
	          {
	            title:'剩余分数',
	            key:'score',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	          },
	          {
	            title:'每周期分数',
	            key:'score',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	          },
	          {
	            title:'状态',
	            key:'status',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	            render:(h,params) => {
	            	return h('Tag',{
	            		props:{
	            			color:this.statusFilter(params.row.status,'color')
	            		}
	            	},this.statusFilter(params.row.status,'text'))
	            }
	          },
	          {
	            title:'题目最后得失分时间',
	            key:'lastScoreTime',
	            align:'center',
	            ellipsis:true,
	            tooltip:true,
	          },
	        ],
	        targetTeamData:[],
            allTargetTeamData: [],
	        targetTeamTotal:0,
	        TargetId:'',
	        timeout:{}
	  	}
	},
	filters:{

	},
	watch:{

	},
	beforeDestroy(){
		clearTimeout(this.timeout)
	},
	mounted(){
    	//this.getAllSence()
    	//this.getAllTargetHost();
    	//this.getAllVmlist();
		if(this.type==0&&this.drillDetail.progress==2&&this.hlConfig==1){
			this.getSceneCycle()
		}
		if(this.hlConfig==2){
			this.targetTeamCol.splice(2,1)
		}
    	//this.queryCtfQuestionList();
			this.getAccessGroupList();
    	this.getTargetTeamList();
    	this.getAllTargetTeamList()
	},
    methods:{
		getSceneCycle(){
			getSceneCycle(this.drillDetail.id).then(res=>{
				if(res.code==1){
					this.number=res.data.number
				} else{
					this.$Message.warning('查询周期信息失败')
				}
			})
		},
    	showAddAndUpdate(info){
    		this.targetModal.show = true;
    		if(!info){
    			this.targetModal.title = '添加题目';
    			this.targetModal.type = 1;
    		}else{
    			this.targetModal.title = '修改题目';
    			this.targetModal.type = 2;
    			this.formValidate = {};
    			this.formValidate = JSON.parse(JSON.stringify(info));
    			this.question = {imageId:this.formValidate.imageId};
    			this.setTeamGroup(this.formValidate.teamId);
    			this.formValidate.externalPort = parseInt(this.formValidate.externalPort);
    		}
    	},
	  	addTargetTeam(){
	  		addTargetTeam(this.formValidate).then(data => {
	  			if(data.code==1){
	  				this.getTargetTeamList();
	  				this.$Message.info('操作成功');
	  				this.handleReset('formValidate');
	  				this.targetModal.show = false;
	  			}else{
	  				this.cancelLoading('targetModal');
	  			}
	  		}).catch(error => {
	  			this.cancelLoading('targetModal');
	  		})
	  	},
	  	modifyTargetTeam(){
	  		modifyTargetTeam(this.formValidate).then(data => {
	  			if(data.code==1){
	  				this.getTargetTeamList();
	  				this.$Message.info('操作成功');
	  				this.handleReset('formValidate');
	  				this.targetModal.show = false;
	  			}else{
	  				this.cancelLoading('targetModal');
	  			}
	  		}).catch(error => {
	  			this.cancelLoading('targetModal');
	  		})
	  	},
	  	saveTargetTeam(){
	  		this.$refs['formValidate'].validate((valid) => {
	            if (valid) {
	            	if(this.targetModal.type == 1){
	            		this.addTargetTeam();
	            	}else{
	            		this.modifyTargetTeam();
	            	}
	            }else{
	            	this.cancelLoading('targetModal');
	            }
	        })
	  	},
        getAllTargetTeamList() {
            getTargetTeamList({
                pageIndex:1,
                pageSize:2147483647,
                sceneId:this.$route.query.id,
                projectId:this.$route.query.prjid
            },).then(data => {
                if(data.code==1){
                    this.allTargetTeamData = data.data.items || data.data;
                }else{

                }
            })
        },
	  	getTargetTeamList(){
	  		clearTimeout(this.timeout);
	  		getTargetTeamList(this.queryTargetTeamInfo).then(data => {
	  			if(data.code==1){
	  				this.targetTeamData = data.data.items || data.data;
	  				this.targetTeamTotal = data.data.total;
	  				if(this.poll){ //如果需要轮询
	  					this.timeout = setTimeout(() => {
		  					this.getTargetTeamList();
		  				},3000)
	  				}
	  			}else{

	  			}
	  		})
	  	},
	  	delTargetTeam(id){
	  		delTargetTeam(id).then(data => {
	  			if(data.code==1){
	  				this.getTargetTeamList();
	  			}else{

	  			}
	  		})
	  	},
	  	cancelLoading(name){
	    	this[name].loading = false;
	      	setTimeout(() => {
	      		this[name].loading = true;
	      	})
	    },
	    typeFilter(val){
	      let str = '';
	      switch (val) {
	      	case 0:str = 'Flag';break;
	        case 1:str = '多个虚拟机Flag相同';break;
	        case 2:str = '多个虚拟机Flag不同';break;
	        case 3:str = '文档';break
	        default:break;
	      }
	      return str;
	    },
	   statusFilter(val,type){

	      let str = '';
	      if(type == 'text'){
	      	switch (val) {
		      	case 1:str = '正常';break;
		        case 2:str = '被攻破';break;
		        case 3:str = '服务异常';break;
		        case 4:str = '被攻破+服务异常';break
				case 5:str= '攻破中';break
		        default:break;
		    }
	      }else{
	      	switch (val) {
		      	case 1:str = 'var(--status-yes)';break;
		        case 2:str = 'var(--status-suspend)';break;
		        case 3:str = 'var(--status-suspend)';break;
		        case 4:str = 'var(--status-no)';break
				case 5:str = 'var(--status-suspend)';break
		        default:break;
		    }
	      }
	      return str;
	    },
	    getAllVmlist(partyId,imageId){
	        let params = {
				page:1,
				pageSize:10000,
				sortBy:'name',
				order:'asc'
			}
	        if(this.question){
	        	params.imageId = this.question.imageId;
	        }
	        if(this.group){
	        	params.party = this.group.partyId;
	        }
			queryVmWithParty(this.routeParams.prjid,params).then(data => {
				if(data.code == 1){
					this.vmlists = data.data.list || data.data;
				}
			})
	    },
	    getAccessGroupList(){
			if(!this.routeParams.id){
				return;
			}
			let params = {
				pageIndex:1,
				pageSize:2147483647,
				testId:this.routeParams.id
			};
			this.selectGroupList = [];
//			this.getPartyList();
			getaccessgrouplist(params).then(data => {
				if(data.code == 1){
					this.accessGroupList = data.data.items;
				}else if(data.code == -2) {
					this.accessGroupList = [];
				}else{
					this.$Message.warning(data.message);
				}
				//this.getUserTaskList();
			})
		},
	    getTargetSize(size){
	      this.queryTargetTeamInfo.pageSize = size;
	      this.getTargetTeamList()
	    },
	    getTargetPage(page){
	      this.queryTargetTeamInfo.pageIndex = page;
	      this.getTargetTeamList()
	    },
	    searchTargetTeam(){
	    	this.queryTargetTeamInfo.pageIndex = 1;
	        this.getTargetTeamList()
	    },
	    setTeamQuestion(val){
	    	if(!val){
	    		return
	    	}
	    	this.question = this.questionList.filter(question => question.chaId == val)[0];
	    	this.formValidate.port = this.question.port;
	    	//this.formValidate.vmId = '';
	    	this.getAllVmlist();
	    },
	    setTeamGroup(val){
	    	if(!val){
	    		return
	    	}
	    	this.group =  this.accessGroupList.filter(group => group.id == val)[0];
	    	this.formValidate.teamName = this.group.name;
	    	//this.formValidate.vmId = '';
	    	this.getAllVmlist();
	    },
	    handleReset (name) {
	      this.$refs[name].resetFields();
	//    this.addTarget = false;
	    },
	    queryCtfQuestionList(){//查询ctf题列表-不分页--不需要环境
	        let obj = {
	          pageIndex:1,
	          pageSize:2147483647,
	          isNeedEnv:'0',
	          //isNeedSubmitFlag:'1',
	          //category:this.autoPro.ctfType.join(',')
	        };
	        let _this = this;
	        queryCtfList(obj).then(data => {
	          if(data.code == 1){
	            _this.questionList = data.data.items.filter(ques => ques.imageId) || data.data;
	            if(_this.questionList.length == 0){
	            	_this.$Message.warning('该工程下没有满足要求的虚拟机');
	            }
	          }else{
	            _this.$Message.warning(data.message);
	          }
	        })
	    },
  }
}
</script>

<style>
  .drillsTable .ivu-poptip-body {
    text-align: left!important;
  }
  .scenesHeader{
    margin-bottom: 16px;
  }
  .drillTables{
    min-height: 300px;
  }
  .drillsTable.ivu-table-wrapper{
    overflow: inherit;
  }
</style>
<style scoped>
  .Titles{
    background: #eeeeee;
    margin: 16px auto;
    padding: 10px 0;
  }
  .targetHeader{
    /*padding: 10px;*/
    margin: 15px 0;
  }
</style>
